package com.tianji.aigc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.stream.StreamUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.aigc.config.ai.SessionProperties;
import com.tianji.aigc.entity.po.ChatSession;
import com.tianji.aigc.entity.vo.ChatSessionVO;
import com.tianji.aigc.enums.MessageTypeEnum;
import com.tianji.aigc.mapper.ChatSessionMapper;
import com.tianji.aigc.memory.MyAssistantMessage;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.service.ChatSessionService;
import com.tianji.aigc.entity.vo.MessageVO;
import com.tianji.aigc.entity.vo.SessionVO;
import com.tianji.common.utils.UserContext;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class ChatSessionServiceImpl extends ServiceImpl<ChatSessionMapper, ChatSession> implements ChatSessionService {

    private final SessionProperties sessionProperties;
    private final ChatMemory chatMemory;
    // 历史消息数量，默认1000条
    public static final int HISTORY_MESSAGE_COUNT = 1000;

    @Override
    public SessionVO createSession(Integer num) {
        SessionVO sessionVO = BeanUtil.toBean(sessionProperties, SessionVO.class);
        // 随机获取examples
        sessionVO.setExamples(RandomUtil.randomEleList(sessionProperties.getExamples(), num));

        // 随机生成sessionId
        sessionVO.setSessionId(IdUtil.fastSimpleUUID());

        // 构建持久化对象，并持久化
        ChatSession chatSession = ChatSession.builder()
                .sessionId(sessionVO.getSessionId())
                .userId(UserContext.getUser())
                .build();
        save(chatSession);

        return sessionVO;
    }

    @Override
    public List<SessionVO.Example> getHotQuestions(Integer num) {
        // 从配置中获取热门问题
        List<SessionVO.Example> examples = sessionProperties.getExamples();
        if (examples == null || examples.isEmpty()) {
            log.warn("热门问题获取失败.");
            return Collections.emptyList();
        }
        // 随机返回指定数量的热门问题
        return RandomUtil.randomEleList(examples, num);
    }

    //查询单个历史对话详情
    @Override
    public List<MessageVO> queryBySessionId(String sessionId) {
        String conversationId = ChatService.getConversationId(sessionId);
        List<Message> messageList = chatMemory.get(conversationId, HISTORY_MESSAGE_COUNT);
        //过滤并转换消息
        return StreamUtil.of(messageList)
                .filter(message -> message.getMessageType() == MessageType.ASSISTANT || message.getMessageType() == MessageType.USER)
                .map(message -> {
                    //如果是MyAssistantMessage类型
                    if(message instanceof MyAssistantMessage){
                        return MessageVO.builder()
                                .content(message.getText())
                                .type(MessageTypeEnum.valueOf(message.getMessageType().name()))
                                .params(((MyAssistantMessage) message).getParams())
                                .build();
                    }
                    //如果不是MyAssistantMessage类型
                    return MessageVO.builder()
                            .content(message.getText())
                            .type(MessageTypeEnum.valueOf(message.getMessageType().name()))
                            .build();
                })
                .toList();


    }

    //增加对话的标题
    @Async//异步更新
    @Override
    public void update(String sessionId, String title, Long userId) {
        List<ChatSession> list = lambdaQuery().eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, userId)
                .list();
        if(list.isEmpty()){
            return;
        }
        //添加对话标题获取列表的第一个聊天会话
        ChatSession chatSession = list.get(0);
        //如果当前第一个会话的标题为空并且传过来的标题有值
        if(StrUtil.isEmpty(chatSession.getTitle()) && StrUtil.isNotEmpty(title)){
            chatSession.setTitle(title);
        }
        //更新时间并保存
        chatSession.setUpdateTime(LocalDateTime.now());
        updateById(chatSession);

    }


    @Override
    public Map<String, List<ChatSessionVO>> queryHistorySession() {
        Long userId = UserContext.getUser();
        //查询历史会话限制条数
        List<ChatSession> list = lambdaQuery().eq(ChatSession::getUserId, userId)
                .isNotNull(ChatSession::getTitle)
                .orderByDesc(ChatSession::getUpdateTime)
                .last("LIMIT 30")
                .list();

        if(CollUtil.isEmpty(list)){
            log.info("没有找到用户:{}历史对话记录",userId);
            return Map.of();
        }

        //转换为需求类型
        List<ChatSessionVO> chatSessionVOS = list.stream().map(chatSession ->
                ChatSessionVO.builder()
                        .sessionId(chatSession.getSessionId())
                        .title(chatSession.getTitle())
                        .updateTime(chatSession.getUpdateTime())
                        .build()
        ).toList();

        final String TODAY = "当天";
        final String LAST_30_DAYS = "最近30天";
        final String LAST_YEAR = "最近1年";
        final String MORE_THAN_YEAR = "1年以上";

        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //按照更新时间进行分组
        return chatSessionVOS.stream().collect(Collectors.groupingBy(vo -> {
            //计算两个日期之间的天数差
            long between = Math.abs(ChronoUnit.DAYS.between(vo.getUpdateTime().toLocalDate(), now));
            if (between == 0) {
                return TODAY;
            } else if (between <= 30) {
                return LAST_30_DAYS;
            } else if (between <= 365) {
                return LAST_YEAR;
            } else {
                return MORE_THAN_YEAR;
            }

        }));
    }


    @Override
    public void deleteHistorySession(String sessionId) {

        //1.获取当前用户
        Long userId = UserContext.getUser();
        //2.删除数据库中数据
        removeByIds(lambdaQuery().eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, userId).list().stream().map(ChatSession::getId).toList());
        //3.删除redis中数据
        chatMemory.clear(ChatService.getConversationId(sessionId));
    }


    @Override
    public void updateTitle(String sessionId, String title) {
        //从索引0开始（包含）到索引100结束（不包含）的子字符串。若title长度不足100，则返回原字符串
        lambdaUpdate().set(ChatSession::getTitle, StrUtil.sub(title, 0,100))
                .eq(ChatSession::getSessionId, sessionId)
                .eq(ChatSession::getUserId, UserContext.getUser())
                .update();
    }
}
